#include "DatabaseService.h"
#include <QDebug>
#include <QRandomGenerator>
#include <TaskManager.h>

DatabaseService::DatabaseService(QObject* parent)
    : QObject(parent)
    , m_databaseManager(DatabaseManager::instance())
    , m_isConnected(false)
{
    m_taskPollingTimer = new QTimer(this);
    m_statusMonitoringTimer = new QTimer(this);

    connect(m_taskPollingTimer, &QTimer::timeout, this, &DatabaseService::onTaskPollingTimeout);
    connect(m_statusMonitoringTimer, &QTimer::timeout, this, &DatabaseService::onStatusMonitoringTimeout);

    log("数据库服务已创建");
}

DatabaseService::~DatabaseService() {
    stopTaskPolling();
    stopStatusMonitoring();

    if (m_isConnected) {
        disconnect();
    }

    log("数据库服务已销毁");
}

bool DatabaseService::initialize(const QString& host, int port,
                                 const QString& database,
                                 const QString& username,
                                 const QString& password) {

    log(QString("正在连接数据库: %1:%2/%3").arg(host).arg(port).arg(database));

    if (m_databaseManager.connect(host, port, database, username, password)) {
        m_isConnected = true;
        m_connectionInfo = QString("%1@%2:%3").arg(username).arg(host).arg(port);

        QString successMsg = QString("✅ 数据库连接成功: %1").arg(m_connectionInfo);
        log(successMsg);

        // 初始化状态记录
        initializeStatusRecord();
        // 预加载常用参数
        // m_currentAlgorithmParams = getAlgorithmParams("DefaultAlgorithm");
        // m_currentMachineParams = getMachineParams("DefaultSetting");

        // if (!m_currentAlgorithmParams.isEmpty()) {
        //     log("默认算法参数加载成功");
        // }
        // if (!m_currentMachineParams.isEmpty()) {
        //     log("默认机台参数加载成功");
        // }

        return true;
    } else {
        QString errorMsg = QString("数据库连接失败: %1").arg(m_databaseManager.lastError());
        log(errorMsg);
        emit databaseConnected(false, errorMsg);

        return false;
    }
}

void DatabaseService::disconnect() {
    stopTaskPolling();
    stopStatusMonitoring();

    m_databaseManager.disconnect();
    m_isConnected = false;

    log("数据库连接已断开");
    emit databaseDisconnected();
}

bool DatabaseService::isConnected() const {
    return m_isConnected && m_databaseManager.isConnected();
}

QString DatabaseService::getConnectionStatus() const {
    if (m_isConnected) {
        return QString("已连接 (%1)").arg(m_connectionInfo);
    } else {
        return "未连接";
    }
}

void DatabaseService::startTaskPolling(int intervalMs) {
    if (!m_isConnected) {
        log("❌ 无法启动任务轮询：数据库未连接");
        return;
    }

    m_taskPollingTimer->start(intervalMs);
    log(QString("✅ 任务轮询已启动，间隔: %1 毫秒").arg(intervalMs));
}

void DatabaseService::stopTaskPolling() {
    if (m_taskPollingTimer->isActive()) {
        m_taskPollingTimer->stop();
        log("⚠️ 任务轮询已停止");
    }
}

void DatabaseService::startStatusMonitoring(int intervalMs) {
    if (!m_isConnected) {
        log("❌ 无法启动状态监控：数据库未连接");
        return;
    }

    m_statusMonitoringTimer->start(intervalMs);
    log(QString("✅ 状态监控已启动，间隔: %1 毫秒").arg(intervalMs));
}

void DatabaseService::stopStatusMonitoring() {
    if (m_statusMonitoringTimer->isActive()) {
        m_statusMonitoringTimer->stop();
        log("⚠️ 状态监控已停止");
    }
}

void DatabaseService::onTaskPollingTimeout() {
    if (!m_isConnected) {
        log("⚠️ 数据库连接已断开，停止任务轮询");
        stopTaskPolling();
        return;
    }

    processPendingTasks();
}

void DatabaseService::onStatusMonitoringTimeout() {
    if (!m_isConnected) {
        log("⚠️ 数据库连接已断开，停止状态监控");
        stopStatusMonitoring();
        return;
    }

    // 更新系统状态（保持原有逻辑）
    updateSystemStatus();
}

void DatabaseService::processPendingTasks() {
    // 查询待执行的任务 (status = 0)
    QVariantMap whereParams;
    whereParams["status"] = static_cast<int>(TaskStatus::PENDING);
    QList<QVariantMap> pendingTasks = m_databaseManager.selectAll(
        "hardware_task_queue",
        {"*"},
        "status = :status",
        whereParams
        );
    if (!pendingTasks.isEmpty()) {
        log(QString("发现 %1 个待处理任务").arg(pendingTasks.size()));
    }

    for (const auto& taskData : pendingTasks) {
        HardwareTaskQueue task = convertToTaskStruct(taskData);
        // 更新任务状态为执行中
        TaskManager::instance().addPendingTask(task);
    }

}

void DatabaseService::executeTask(const QVariantMap& task) {
    qint64 taskId = task["id"].toLongLong();
    QString taskName = task["task_name"].toString();  // 修改字段名
    int taskType = task["task_type"].toInt();         // 修改字段名

    log(QString("🔄 执行任务 #%1: %2 - 类型: %3").arg(taskId).arg(taskName).arg(taskType));
    // emit taskReceived(task);

    // 更新任务状态为执行中
    QVariantMap updateData;
    updateData["status"] = 1;
    // 移除不存在的 execute_times 字段

    QVariantMap whereParams;
    whereParams["id"] = taskId;

    if (!m_databaseManager.updateData("hardware_task_queue", updateData, "id = :id", whereParams)) {
        QString errorMsg = QString("无法更新任务状态: %1").arg(m_databaseManager.lastError());
        log("❌ " + errorMsg);
        emit taskExecuted(taskId, false, errorMsg);
        return;
    }

    // 执行具体的业务逻辑
    bool success = false;
    QString resultMsg;

    // 根据任务类型执行操作
    switch (taskType) {
    case 1: // POLISH_START
        log("执行开始抛光命令");
        success = true;
        resultMsg = "抛光开始成功";
        break;
    case 2: // POLISH_STOP
        log("执行停止抛光命令");
        success = true;
        resultMsg = "抛光停止成功";
        break;
    case 3: // TEMPERATURE_SET
        log("执行温度设置命令");
        success = true;
        resultMsg = "温度设置成功";
        break;
    case 4: // PRESSURE_ADJUST
        log("执行压力调整命令");
        success = true;
        resultMsg = "压力调整成功";
        break;
    default:
        log(QString("⚠️ 未知任务类型: %1").arg(taskType));
        resultMsg = QString("未知任务类型: %1").arg(taskType);
        break;
    }

    // 更新任务最终状态
    QVariantMap finalUpdateData;
    if (success) {
        finalUpdateData["status"] = 2; // 执行成功
        finalUpdateData["end_time"] = QDateTime::currentDateTime();
        finalUpdateData["result_message"] = resultMsg;
        log(QString("✅ 任务 #%1 执行成功: %2").arg(taskId).arg(resultMsg));
    } else {
        finalUpdateData["status"] = 3; // 执行失败
        finalUpdateData["result_message"] = resultMsg;
        log(QString("❌ 任务 #%1 执行失败: %2").arg(taskId).arg(resultMsg));
    }

    if (!m_databaseManager.updateData("hardware_task_queue", finalUpdateData, "id = :id", whereParams)) {
        log(QString("⚠️ 无法更新任务最终状态: %1").arg(taskId));
    }

    emit taskExecuted(taskId, success, resultMsg);
}

HardwareTaskQueue DatabaseService::convertToTaskStruct(const QVariantMap& taskData) {
    HardwareTaskQueue task;
    task.fromVariantMap(taskData);
    return task;
}

void DatabaseService::updateSystemStatus() {
    // 获取当前系统状态（模拟数据）
    QVariantMap currentStatus = getCurrentMachineStatus();

    // 更新状态表（原有逻辑）
    if (updateMachineStatus(currentStatus)) {
        emit statusUpdated(currentStatus);

        // 同时更新内部状态表缓存
        StatusTable newStatus = convertToStatusTable(currentStatus);
        updateStatusTable(newStatus);
    } else {
        log("❌ 状态更新失败");
    }
}

QVariantMap DatabaseService::getAlgorithmParams(const QString& algorithmName, const QString& version) {
    if (!m_isConnected) {
        log("❌ 无法获取算法参数：数据库未连接");
        return QVariantMap();
    }

    QVariantMap whereParams;
    whereParams["algorithm_name"] = algorithmName;
    whereParams["algorithm_version"] = version;
    whereParams["is_active"] = 1;

    QVariantMap params = m_databaseManager.selectOne(
        "param_algorithm",
        {"*"},
        "algorithm_name = :algorithm_name AND algorithm_version = :algorithm_version AND is_active = :is_active",
        whereParams,
        {"s_PreProcess3DSPara", "s_DefectPlateBPara", "s_JggyPara"}
        );

    if (params.isEmpty()) {
        log(QString("⚠️ 未找到算法参数: %1 v%2").arg(algorithmName).arg(version));
    } else {
        log(QString("✅ 已加载算法参数: %1 v%2").arg(algorithmName).arg(version));
    }

    return params;
}

QVariantMap DatabaseService::getMachineParams(const QString& settingName) {
    if (!m_isConnected) {
        log("❌ 无法获取机台参数：数据库未连接");
        return QVariantMap();
    }

    QVariantMap whereParams;
    whereParams["setting_name"] = settingName;
    whereParams["is_active"] = 1;

    QVariantMap params = m_databaseManager.selectOne(
        "param_machine",
        {"*"},
        "setting_name = :setting_name AND is_active = :is_active",
        whereParams,
        {"s_BasicSettings", "s_PointSettings", "s_DeviceBehavior", "s_ToolParameters",
         "s_FixtureParameters", "s_WorkpieceParameters", "s_ProcessParameters",
         "s_MachineInfo", "s_CameraParameters", "s_DatabaseParameters"}
        );

    if (params.isEmpty()) {
        log(QString("⚠️ 未找到机台参数: %1").arg(settingName));
    } else {
        log(QString("✅ 已加载机台参数: %1").arg(settingName));
    }
    return params;
}

bool DatabaseService::updateMachineStatus(const QVariantMap& statusData) {
    if (!m_isConnected) {
        log("❌ 无法更新机台状态：数据库未连接");
        return false;
    }

    // 创建更新数据副本，确保包含ID
    QVariantMap updateData = statusData;
    updateData["id"] = 1; // 确保包含固定ID

    bool success = m_databaseManager.replaceData("status_table", updateData);
    if (success) {
    } else {
        log(QString("❌ 机台状态更新失败: %1").arg(m_databaseManager.lastError()));
    }

    return success;
}

bool DatabaseService::addRecord(const QVariantMap& recordData) {
    if (!m_isConnected) {
        log("❌ 无法添加记录：数据库未连接");
        return false;
    }

    bool success = m_databaseManager.insertData("record_table", recordData);
    if (success) {
        log("✅ 运行记录已添加");
    } else {
        log(QString("❌ 运行记录添加失败: %1").arg(m_databaseManager.lastError()));
    }

    return success;
}

bool DatabaseService::initializeStatusRecord()
{
    if (!m_isConnected) {
        log("❌ 无法初始化状态记录：数据库未连接");
        return false;
    }

    // 检查状态表是否已有记录
    QVariantMap existingStatus = m_databaseManager.selectOne("status_table", {"id"});

    if (existingStatus.isEmpty()) {
        // 没有记录，创建初始状态
        QVariantMap initialStatus = generateMachineStatusData(0, 0); // 空闲状态，无报警
        initialStatus["id"] = 1; // 设置固定ID

        bool success = m_databaseManager.insertData("status_table", initialStatus);
        if (success) {
            log("✅ 状态记录初始化成功");
            // 加载到缓存
            loadStatusTable();
        } else {
            log(QString("❌ 状态记录初始化失败: %1").arg(m_databaseManager.lastError()));
        }
        return success;
    } else {
        log("✅ 状态记录已存在");
        // 加载到缓存
        loadStatusTable();
        return true;
    }
}

QVariantMap DatabaseService::generateMachineStatusData(int runStatus, int alarmStatus) {
    QVariantMap status;

    // 核心状态字段
    status["c_run_status"] = runStatus;
    status["c_alarm_status"] = alarmStatus;
    status["c_control_mode"] = 1;
    status["c_machine_mode"] = 1;

    // 连接状态字段
    status["c_camera_connected"] = 1;
    status["c_device_connected"] = 1;

    // 主轴加工参数 - 修正字段名
    QRandomGenerator random(QDateTime::currentMSecsSinceEpoch());

    status["s_temperature"] = 25.0 + random.generateDouble() * 10;
    status["torque"] = 5.0 + random.generateDouble() * 2;  // 新增扭矩
    status["s_spindle_speed"] = 2000 + random.bounded(1000);
    status["s_feed_speed"] = 100 + random.bounded(50);
    status["s_point_motion_speed"] = 500 + random.bounded(200);
    status["s_tool_diameter"] = 6.0;
    status["s_line_spacing"] = 2.5;
    status["s_total_cutting_depth"] = 10.0;
    status["s_clearance_speed"] = 800;
    status["s_work_surface_height"] = 50.0;
    status["s_cutting_depth"] = 1.0;
    status["s_step_distance"] = 0.5;

    // 夹具状态
    status["f_fixture_status"] = "00000";

    // 坐标位置数据
    double baseX = 100.0 + random.generateDouble() * 10;
    double baseY = 200.0 + random.generateDouble() * 10;
    double baseZ = 50.0 + random.generateDouble() * 5;

    status["p_absolute_position"] = QString("%1,%2,%3").arg(baseX).arg(baseY).arg(baseZ);
    status["p_relative_position"] = QString("%1,%2,%3").arg(baseX - 10).arg(baseY - 10).arg(baseZ - 5);
    status["p_work_position"] = QString("%1,%2,%3").arg(baseX).arg(baseY).arg(baseZ);
    status["p_remaining_distance"] = QString("%1,%2,%3").arg(500 - baseX).arg(500 - baseY).arg(100 - baseZ);

    // 时间字段
    status["status_time"] = QDateTime::currentDateTime();

    return status;
}

QVariantMap DatabaseService::generateSimulatedMachineStatus() {
    static int statusCycle = 0;
    statusCycle = (statusCycle + 1) % 10;

    int runStatus = 2;
    int alarmStatus = 0;

    switch (statusCycle) {
    case 0: runStatus = 0; break;
    case 1: runStatus = 1; break;
    case 2: runStatus = 2; break;
    case 3: runStatus = 3; break;
    case 8:
        runStatus = 2;
        alarmStatus = 1;
        break;
    default: runStatus = 2; break;
    }

    return generateMachineStatusData(runStatus, alarmStatus);
}

StatusTable DatabaseService::getCurrentStatusTable()
{
    return m_currentStatusTable;
}

bool DatabaseService::updateStatusTable(const StatusTable &status)
{
    if (!m_isConnected) {
        log("❌ 无法更新状态表：数据库未连接");
        return false;
    }

    // 检查状态是否发生变化
    if (m_currentStatusTable.hasChanged(status)) {
        m_currentStatusTable = status;
        m_currentStatusTable.updateStatusTime();

        // 保存到数据库
        bool success = saveStatusTable(m_currentStatusTable);
        if (success) {
            emit statusTableChanged(m_currentStatusTable);

            // 发出具体状态变化信号
            if (m_currentStatusTable.cameraConnected != status.cameraConnected) {
                emit cameraConnectionChanged(m_currentStatusTable.cameraConnected);
            }
            if (m_currentStatusTable.deviceConnected != status.deviceConnected) {
                emit deviceConnectionChanged(m_currentStatusTable.deviceConnected);
            }
            if (m_currentStatusTable.runStatus != status.runStatus) {
                emit runStatusChanged(static_cast<int>(m_currentStatusTable.runStatus));
            }
        }
        return success;
    }

    return true;
}

bool DatabaseService::saveStatusTable(const StatusTable &status)
{
    if (!m_isConnected) {
        log("❌ 无法保存状态表：数据库未连接");
        return false;
    }

    QVariantMap statusData = convertFromStatusTable(status);
    statusData["id"] = 1; // 确保包含固定ID

    bool success = m_databaseManager.replaceData("status_table", statusData);
    if (success) {
    } else {
        log(QString("❌ 状态表保存失败: %1").arg(m_databaseManager.lastError()));
    }

    return success;
}

StatusTable DatabaseService::loadStatusTable()
{
    if (!m_isConnected) {
        log("❌ 无法加载状态表：数据库未连接");
        return StatusTable();
    }

    // 从数据库加载状态表
    QVariantMap statusData = m_databaseManager.selectOne("status_table", {"*"});
    if (!statusData.isEmpty()) {
        m_currentStatusTable = convertToStatusTable(statusData);
        log("✅ 状态表已从数据库加载");

        // 发出状态变化信号
        emit statusTableChanged(m_currentStatusTable);
    } else {
        log("⚠️ 未找到状态表记录，使用默认状态");
        m_currentStatusTable = StatusTable(); // 使用默认状态
    }

    return m_currentStatusTable;
}

void DatabaseService::setCameraConnected(bool connected)
{
    StatusTable newStatus = m_currentStatusTable;
    newStatus.cameraConnected = connected ? 1 : 0;
    newStatus.updateStatusTime();
    updateStatusTable(newStatus);
}

void DatabaseService::setDeviceConnected(bool connected)
{
    StatusTable newStatus = m_currentStatusTable;
    newStatus.deviceConnected = connected ? 1 : 0;
    newStatus.updateStatusTime();
    updateStatusTable(newStatus);
}

void DatabaseService::setRunStatus(int status)
{
    StatusTable newStatus = m_currentStatusTable;
    newStatus.runStatus = static_cast<RunStatus>(status);
    newStatus.updateStatusTime();
    updateStatusTable(newStatus);
}

void DatabaseService::setAlarmStatus(int status)
{
    StatusTable newStatus = m_currentStatusTable;
    newStatus.alarmStatus = static_cast<AlarmStatus>(status);
    newStatus.updateStatusTime();
    updateStatusTable(newStatus);
}


QVariantMap DatabaseService::getCurrentMachineStatus() {
    // 在实际应用中，这里应该从硬件读取真实数据
    // 现在使用模拟数据
    return generateSimulatedMachineStatus();
}

QJsonObject DatabaseService::convertStatusToJson(const QVariantMap& status) {
    QJsonObject json;
    for (auto it = status.begin(); it != status.end(); ++it) {
        json[it.key()] = QJsonValue::fromVariant(it.value());
    }
    return json;
}

void DatabaseService::log(const QString& message) {
    qDebug() << "[DatabaseService]" << message;
    emit logMessage(message);
}

StatusTable DatabaseService::convertToStatusTable(const QVariantMap &statusData)
{
    StatusTable statusTable;
    statusTable.fromVariantMap(statusData);
    return statusTable;
}

QVariantMap DatabaseService::convertFromStatusTable(const StatusTable &statusTable)
{
    return statusTable.toVariantMap(true);
}

QString DatabaseService::getRunStatusText(RunStatus status)
{
    switch (status) {
    case RunStatus::Idle: return "空闲";
    case RunStatus::Initialized: return "已初始化";
    case RunStatus::Running: return "运行中";
    case RunStatus::Paused: return "暂停";
    default: return "未知";
    }
}
